package dian.qing.li.demo.security.config.security;

import com.pactera.redis.utils.RedisUtils;
import dian.qing.li.demo.security.constants.RedisKey;
import dian.qing.li.demo.security.service.UserService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

/**
 * 用户详情
 *
 * @author: liqingdian
 **/
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String userCode) throws UsernameNotFoundException {
        LoginUser login = userService.login(userCode);
        // 用户连续5次登陆失败，则锁定用于5分钟
        String lockedKey = RedisUtils.redisKey(RedisKey.LOGIN_LOCKED, login.getUsername());
        Integer loginCount = RedisUtils.get(lockedKey, Integer.class);
        boolean locked = ObjectUtils.isNotEmpty(loginCount) && loginCount < 0;
        UserDetails details = User.builder().username(login.getUsername())
                .password(login.getPassword())
                .disabled(login.isDisabled())
                .accountLocked(locked)
                .accountExpired(login.isDisabled())
                .credentialsExpired(false)
                .authorities(login.getAuthorities().toArray(new String[0]))
                .build();
        return details;
    }
}
